/**
 * Created by leo on 5/31/16.
 */

var express = require('express');
var router = express.Router();
var Room = require('../models/room');
var Device = require('../models/device')

router.get('/', function(req, res) {
    Room.getRooms(function(err, room) {
        if (err) {
            throw err;
        }
        res.json(room);
    });
});

router.get('/:_id', function(req, res) {
    Room.getRoomById(req.params._id, function(err, room) {
        if (err) {
            throw err;
        }
        res.json(room);
    });
});

router.post('/', function(req, res) {
    var room = req.body;
    Room.addRoom(room, function(err, room) {
        if (err) {
            throw err;
        }
        res.json(room);
    });
});

router.put('/:_id', function (req, res) {
    var id = req.params._id;
    var room = req.body;
    Room.updateRoom(id, room, {}, function(err, room) {
        if (err) {
            throw err;
        }
        res.json(room);
    });
});

router.delete('/:_id', function (req, res) {
    var id = req.params._id;
    Room.removeRoom(id, function(err, room) {
        if (err) {
            throw err;
        }
        res.json(room);
    });
});


// 房间详情
router.get('/:_id/devices', function(req, res, next) {
    //console.log('房间: ' + req.params._id);

    Room.findOne({
            _id: req.params._id,
        })
        .exec(function(err, room) {
            if (err) {
                throw err;
            }

            // 查询匹配为空
            if (!room) {
                return res.send('未找到房间');
            }

            // 查询有效
            var id = room._id;
            var roomName = room.name;
            Device.find({})
                .where('room')
                .in([id])
                .sort()
                .exec(function(err, devices) {
                    if (err) {
                        return res.send(err);
                    }

                    res.json(devices);
                });
        });
});

module.exports = router;
